/**
 * 
 */
package bi.uc.client;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.bi_uc.www.R;

import bi.uc.login.Info;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author Administrator
 *
 */
public class MobileSearchActivity extends Activity implements OnClickListener, OnTouchListener,Runnable {
	EditText mobileNum;
	ImageButton search;
	String txTelString;
	ListView listView;
	Info info = Info.getInfo();
	Handler handler;
	ArrayList<String> cardNums;
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.mobilesearch);
		handler = new Handler();
		mobileNum = (EditText) findViewById(R.id.mobileNum);
		search = (ImageButton) findViewById(R.id.searchbtn);
		listView = (ListView) findViewById(R.id.listview);
		search.setOnClickListener(this);
		search.setOnTouchListener(this);
	}
	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);  
		txTelString = mobileNum.getText().toString();
		if ("".equals(txTelString)) {
			Toast.makeText(this, "请输入手机号码！", Toast.LENGTH_SHORT).show();
			return;
		}else if (!isMobileNO(txTelString)) {
			Toast.makeText(this, "手机号码输入格式不正确！", Toast.LENGTH_SHORT).show();
			return;
		}
		if (info.stopFlag) {
			Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
					.show();
		} else {
			new Thread(this).start();
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			send();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 
	 */
	private void send() throws Exception{
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
				// TODO Auto-generated method stub
						String Url = "http://bi.bi-uc.com/BI.api";
						/*String Body = "Action=PDA-充值&商家=" + info.employID + "&店面="
								+ info.shopID + "&操作员=" + info.userID + "&卡号=" + cardNumString
								+ "&充值金额=" + moneyString;
						Log.d("data", Body);*/
						HttpPost httpRequest = new HttpPost(Url);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-读手机号");
						NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);				
						NameValuePair pair3 = new BasicNameValuePair("手机号", txTelString);
						

						params.add(pair1);
						params.add(pair2);
						params.add(pair3);
						
						HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
						httpRequest.setEntity(entity);
						DefaultHttpClient client = new DefaultHttpClient();
						HttpResponse response = client.execute(httpRequest);
						if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
							/*InputStream in = response.getEntity().getContent();
							BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
							StringBuffer responseMessage = new StringBuffer();
							int charCount = -1;  
							   while ((charCount = br.read()) != -1) {  
								    responseMessage.append((char) charCount);  
								   }  
							   Log.d("tag", responseMessage.toString());*/
							InputStream in = response.getEntity().getContent();// 接收服务器的数据
							XmlPullParserFactory pullParserFactory = XmlPullParserFactory
									.newInstance();    // 获取XmlPullParser的实例					
							final XmlPullParser parser = pullParserFactory.newPullParser();
							InputStreamReader responseReader = new InputStreamReader(in,
									"UTF-8");
							parser.setInput(responseReader);
							parser.next();
							int eventType = parser.getEventType();
							if (eventType != XmlPullParser.END_DOCUMENT) {
								if (eventType == XmlPullParser.START_TAG
										&& parser.getName().equals("DATA")) {
									showMobileNums(parser, eventType);
								}
								else if (eventType == XmlPullParser.START_TAG
										&& parser.getName().equals("XML")) { // String result = parser.getAttributeValue(0);
									String result = parser.getAttributeValue(null, "EXEC");
									if (result.equals("False")) {
										runOnUiThread(new Runnable() {
											@Override
											public void run() {
												Toast.makeText(MobileSearchActivity.this,parser.getAttributeValue(null, "错误消息"),
														Toast.LENGTH_SHORT).show();
											}
										});			
									} 
								}								
							}
							in.close();
						
							responseReader.close();
						}
						else
						{
							runOnUiThread(new Runnable() {				
								@Override
								public void run() {
									Toast.makeText(MobileSearchActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
									}
							});	
						}
			

	}
	
	/**
	 * @param parser
	 * @param eventType
	 */
	private void showMobileNums(XmlPullParser parser, int eventType) throws Exception{
		// TODO Auto-generated method stub
		cardNums = new ArrayList<String>();
		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			// 文档开始
			case XmlPullParser.START_DOCUMENT:
				// 初始化
				// persons = new ArrayList<Person>();
				break;
			case XmlPullParser.START_TAG: // 开始标签
				if ("ROW".equals(parser.getName())) {					
					cardNums.add(parser.getAttributeValue(null, "pCard_卡号"));
					Log.d("pCard_卡号", parser.getAttributeValue(null, "pCard_卡号"));
				}
				
				break;
			case XmlPullParser.TEXT:
				break;
			case XmlPullParser.END_TAG:// 结束标签
				break;
			default:
				break;
			}
			// 下一个节点
			eventType = parser.next();
		}
		handler.post(new Runnable() {
			@Override
			public void run() {
				listView.setAdapter(new ArrayAdapter<String>(MobileSearchActivity.this, R.layout.cardnums, cardNums));
				listView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?>  parent, View view, int position,
							long id) {
						Intent intent = getIntent();
						intent.putExtra("cardNum", cardNums.get(position));
						setResult(RESULT_OK, intent);
						finish();				
					}
					
				});
			}
			});
	}
	public boolean isMobileNO(String mobiles) {

        Pattern p = Pattern.compile("^1[3|4|5|8]\\d{9}(,1[3|4|5|8]\\d{9})*$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }
	/* (non-Javadoc)
	 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
	 */
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.searchbtn:
			
			if (event.getAction() == MotionEvent.ACTION_UP) {
				search.setBackgroundColor(Color.TRANSPARENT);
			}else if (event.getAction() == MotionEvent.ACTION_DOWN) {
				search.setBackgroundColor(Color.rgb(51, 102, 153));
			}
			break;
		default:
			
			break;
		}
		return false;
		
	}
	/* (non-Javadoc)
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		 if  (event.getAction() == MotionEvent.ACTION_DOWN) {  

            System.out.println("down" );  

            if  (this .getCurrentFocus() !=  null ) {  

                if  (this .getCurrentFocus().getWindowToken() !=  null ) {  

                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),  

                            0);  
                }  

            }  
        }  
		return super.onTouchEvent(event);
	}
}
